Write a function:

class Solution { public int[] solution(int[] A, int K); }

that, given a zero-indexed array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given array A = [3, 8, 9, 7, 6] and K = 3, the function should return [9, 7, 6, 3, 8].

Assume that:

    N and K are integers within the range [0..100];
    each element of array A is an integer within the range [−1,000..1,000].

In [3]:
A = [3, 8, 9, 7, 6] 

print A[-1:]

B = A[-1:] + A[1:]

print B

B = A[-1:] + A[:-1]

print B

K = 3

print K

print len(A)

C = B = A[-(3):] + A[:-(3)]

print C


[6]
[6, 8, 9, 7, 6]
[6, 3, 8, 9, 7]
3
5
[9, 7, 6, 3, 8]

Cyclic Rotation


In [9]:
def solution(A,K):
    
    if len(A) == 0:
        return A
    elif K >= len(A):
        M = K - (K/len(A)) * len(A)
        return A[-(M):] + A[:-(M)]
    
    else:
        return A[-(K):] + A[:-(K)]

In [10]:
print solution(A,K)


[9, 7, 6, 3, 8]

In [ ]: